#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:命名切片
问题: 如果你的程序包含了大量无法直视的硬编码切片，并且你想清理一下代码
提示 : 
    1. 调用切片的 slice.indices(size) 方法, 有效避免出现 IndexError 异常
"""

record = '....................100 .......513.25 ..........'
print(f"{record = }")

def recipe1():
    """硬编码切片"""
    cost = int(record[20:23]) * float(record[31:37])
    print(f"{cost = }")


def recipe2():
    """命名切片"""
    SHARES = slice(20, 23)
    PRICE = slice(31, 37)
    cost = int(record[SHARES]) * float(record[PRICE])
    print(f"{cost = }")
    print(f"{SHARES.start = }")
    print(f"{SHARES.stop = }")
    print(f"{SHARES.step = }")


def recipe3():
    """内置的 slice() 函数创建了一个切片对象。所有使用切片的地方都可以使用切片对象"""
    items = [0, 1, 2, 3, 4, 5, 6]
    print(f"{items = }")
    print(f"{items[2:4] = }")

    a = slice(2, 4)
    print(f"{items[a] = }")

    items[a] = [10, 11]  # 覆盖
    print(f"{items = }")

    del items[a]  # 删除
    print(f"{items = }")


def recipe4():
    """通过调用切片的 indices(size) 方法将它映射到一个已知大小的序列上，有效避免出现 IndexError 异常"""
    s = 'HelloWorld' 
    print(f"{s = }")

    a = slice(5, 50, 2)
    print(f"{a.indices(len(s)) = }")
    for i in range(*a.indices(len(s))):
        print(f"{s[i] = }")

def recipe5():
    """IndexError 异常"""
    s = 'HelloWorld'
    print(f"{s = }")
    for i in range(*(5, 50, 2)):
       print(f"{s[i] = }") # IndexError: string index out of range

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()    
    print('recipe5'.center(20, '*'))
    recipe5()    

if __name__ == '__main__':
    main()
